package com.hdc.hdc.warehouseManage.utill;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 自定义HttpURLConnection线程池，试用
 * @author gjy
 *
 * 2018年3月19日下午6:27:29
 */
@Component
public class HttpConnectionPool {
	
	
	private static final Logger log = LoggerFactory.getLogger(HttpConnectionPool.class);

	private int max_pool_size = 0;
	
	private int doTimes = 0;
	//存储线程
	private Map<String, Object> pool = new ConcurrentHashMap<String, Object>();
	
	
	public HttpURLConnection returnConnection(String interfaceUrl) throws IOException {
		
		log.info("请求连接---start");
		
		if (IsNotNullValit.StringIsNotNull(interfaceUrl)) {
			
			if (pool.get(interfaceUrl) != null) {
				
				URL url = (URL) pool.get(interfaceUrl);
				
				if (pool.get(url.toString())!=null) {
					
					HttpURLConnection conn = (HttpURLConnection) pool.get(url.toString());
					
					return conn;
					
				}else {
					HttpURLConnection conn = null;
					try {
						conn = initHttpURLConnection(url);
					} catch (Exception e) {
						e.printStackTrace();
						log.error("超时回滚");
						if (e.getMessage().indexOf("connect time out")>0) {
							conn = initHttpURLConnection(url);
						}
					}
					return conn;
				}
				
			}else {
				
				try {
					pool = initPool(interfaceUrl);
					
					if (pool != null) {
						this.returnConnection(interfaceUrl);
					}
				} catch (Exception e) {
					e.printStackTrace();
					
					log.error("超时回滚");
					
					if (e.getMessage().indexOf("connect time out")>0) {
						pool = initPool(interfaceUrl);
						
						if (pool != null) {
							this.returnConnection(interfaceUrl);
						}
					}
				}
				
			}
			
		}
		
		return null;
	}


	private Map<String, Object> initPool(String interfaceUrl) throws IOException {
		
		log.info("------------huc创建线程池*************************************,执行次数:"+(doTimes++));

		this.pool = new ConcurrentHashMap<String, Object>();

		// 需要请求的连接
		URL url = new URL(interfaceUrl);
		
		HttpURLConnection conn =  this.initHttpURLConnection(url);
		pool.put(interfaceUrl, url);
		pool.put(url.toString(), conn);
		//线程保存时间半个小时
		pool.put("1000*60*60", max_pool_size++);
		
		timer(interfaceUrl);

		return pool;
	}


	/**
	 * 通过url打开连接
	 * @param url
	 * @return
	 * @throws IOException 
	 */
	private HttpURLConnection initHttpURLConnection(URL url) throws IOException {

		// 打开连接
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 设置请求方式和消息头以及超时时间
		conn.setRequestMethod("POST");
		conn.setConnectTimeout(30000);
		// 设置是否允许对外输出数据
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");

		return conn;
	}
	
	
	private void timer(String interFaceUrl) {
		
		log.info("计数器执行");
		
		//定义为守护进程
		Timer timer = new Timer();
		
		timer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				
				if (pool==null) {
				}else {
					Integer maxSize = (Integer) pool.get("1000*60*60");
					
					if (maxSize == null) {
						log.info("pool被清过了");
					}else {
						if(pool.isEmpty()) {
							log.info("pool被清过了");
						}else {
							URL url = (URL) pool.get(interFaceUrl);
							if (url != null) {
								
								HttpURLConnection conn = (HttpURLConnection) pool.get(url.toString());
								if (conn!=null) {
									conn.disconnect();
								}else {
									pool.remove(url.toString());
								}
							}else {
								pool.remove(interFaceUrl);
							}
						}
					}
					
				}
				
			}
		},100, 1000*60*60);
		
	}
	
	


}
